<template>
  <div class="block">
    <el-image v-loading="loading" :src="url" fit="fill" />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, onActivated, ref, watch } from 'vue'
import { useRouter } from "vue-router";
import { isElectron } from "@/utils";
import { useStore } from "@/store/store";
import { userGetOR, userGetStatusService, userGetInfoService, findConversationInfo, getShortcutPromptList, getSystemMap, getFunctionOptionList } from "@/utils/api.ts";
import { v4 as uuidv4 } from 'uuid';
import propmpts from "@/config";

const store = useStore();
const { setUserInfo } = store;
const url = ref('');
const loading = ref(false);
const loadingText = ref('登录中...');
const router = useRouter()
let timerId;

const { ipcRenderer } = require("electron");
ipcRenderer.on("sysLogout", (event, obj) => {
  console.log(obj)
  if (obj.sysLogout) init('update');
});

onMounted(() => {
  // handleLogin('mounted');
  init('mounted');
})

const init = async (flag) => {
  console.log('初始化');
  const uuid = uuidv4();
  const info = await userGetOR({ uuid }) //调用注册接口并传参
  if (Number(info.code) === 204) {
    handleLogin(flag);//204代表已登录,就不需要执行二维码相关操作了，直接登录
    return;
  }
  url.value = info.data.qr_code;
  console.log(info);

  timerId = setInterval(async function () {
    const dataStatus = await userGetStatusService({ uuid: info.data.key })
    console.log(dataStatus.data.status)
    // 注：status：0 未处理，1 扫码中 2 扫码成功
    if (dataStatus.data.status === 1) {
      loading.value = true;
    } else {
      loading.value = false;
      if (dataStatus.data.status === 2) {
        clearInterval(timerId);

        const userInfo = await userGetInfoService({ uuid: info.data.key });
        console.log(userInfo)
        if (userInfo.code === '0') {
          loadingText.value = '登录成功!';
          handleLogin(flag);
        }
      }
    }
  }, 500)
}

const initIcon = async () => {
  const info = await getShortcutPromptList();
  let defaultPropmpts = []
  if (info.message === 'success') {
    defaultPropmpts = info.data.map(item => {
      return {
        id: item.id,
        text: item.prompt_name,
        placholder: item.prompt_value,
        icon: item.icon,
        type: "all",
      }
    })
  }
  localStorage.setItem("propmpts", JSON.stringify(defaultPropmpts));
}

// 登录
async function handleLogin(flag) {
  let token = "test";
  localStorage.setItem("_token_", token);

  if (isElectron()) {
    try {
      initIcon();
      const info = await findConversationInfo({
        "limit": 99,	// 获取的聊天记录数目
        "offset": 0 // 偏移量
      })
      
      localStorage.setItem("userInfo", JSON.stringify(info.data) || '');
      const infoMap = await getSystemMap();
      localStorage.setItem("infoMap", JSON.stringify(infoMap.data) || '');
      const infoOptionList = await getFunctionOptionList();
      localStorage.setItem("infoOptionList", JSON.stringify(infoOptionList.data) || '');
      console.log(infoMap, infoOptionList);
    } catch (e) {
      const mockdata = {
        "category": "default",
        "kind": "default",
        "user_id": 'qydqudv',
        "convId": 'duqgdqfdad',
        "messages": []	// 聊天记录
      }
      localStorage.setItem("userInfo", JSON.stringify(mockdata) || '');
    }

    const { ipcRenderer } = require("electron")
    
    if (flag == 'mounted') {
      await ipcRenderer.invoke("isLogin");//第一次登录
    } else {
      await ipcRenderer.invoke("isLoginUpdate");//注销后再登录
    }
  } else {
    router.push("/search");
  }
}

onUnmounted(() => {
  console.log('onUnmounted')
  clearInterval(timerId)
})
</script>

<style scoped>
.dayDiv {
  width: 960px;
  height: 540px;
}

.block {
  width: 176px;
  height: 176px;
  border: 1px solid #EEEEEE;
}
</style>
